<?php
/*
@author: wjf
@contact: Hurrican
@software: PhpStorm
@create: 2022/8/8 13:35
*/
declare(strict_types=1);
namespace app\store\service\agent;

use app\common\service\BaseService;
use app\store\model\agent\Channel;
use app\store\model\agent\Rel;
use app\store\model\User;
use app\store\model\User as UserModel;
use think\Exception;
use think\facade\Db;
use app\store\model\agent\Promoter as PromoterModel;

class Promoter extends BaseService
{
    public function getList($params):array
    {
        $condition = [];
        if(!empty($params['channel_id'])){
            $condition[] = ['fw_agent_promoter.channel_id','=',$params['channel_id']];
        }
        if(!empty($params['user_id'])){
            $condition[] = ['fw_agent_promoter.user_id','=',$params['user_id']];
        }
        $userWhere = [];
        if(!empty($params['nick_name'])){
            $userWhere[] = ['nick_name','like',"%{$params['nick_name']}%"];
        }
        if(!empty($params['mobile'])){
            $userWhere[] = ['mobile','=',$params['mobile']];
        }
        return PromoterModel::with(['channel','user'])
            ->where('is_del',0)
            ->where($condition)
            ->hasWhere('user', $userWhere)
            ->paginate($params['limit'] ?? 15)
            ->each(function (&$item){
                $item['total_develop_num'] = $this->getTotalDevelopNum($item['user_id']);  //累计发展玩家
                $item['username'] = $item['user']['username'] ?? '';
            })
            ->toArray();
    }

    /**累计发展玩家
     * @param $agent_id
     */
    public  function getTotalDevelopNum($agent_id): int
    {
        return Rel::where(['promoter_user_id' => $agent_id,'is_del' => 0])->count();
    }

    /**
     * @param $params
     * @return bool
     */
    public function save($params):bool
    {
        if(!empty($params['password']) && !empty($params['confirm_password'])){
            if($params['password'] != $params['confirm_password']){
                throwError('两次密码输入不一致,请重新输入');
            }
        }
        Db::startTrans();
        try {
            if(empty($params['id'])){
                //新增
                if(empty($params['password']) || empty($params['confirm_password'])){
                    throw new Exception('密码不能为空字符串');
                }
                $user = User::where('is_delete',0)->where('mobile',$params['mobile'])->find();
                if(!$user){
                    $user = User::create([
                        'mobile' => $params['mobile'],
                        'nick_name' => $params['nick_name'],
                        'username' => $params['username'],
                        'password' => encryption_hash((string)$params['password'])
                    ]);
                    if(!$user->user_id){
                        throw new Exception('insert user error');
                    }
                }else{
                    $user->username = $params['username'];
                    $user->password = encryption_hash((string)$params['password']);
                    $user->save();
                }
                //校验是否为渠道用户，渠道用户和推广用户只能为一个角色
                $channel_user = Channel::where(['user_id' => $user->user_id,'is_del' => 0])->find();
                if($channel_user){
                    throw new Exception('已经是一级代理用户了');
                }

                $channel_user = Channel::where(['id' => $params['channel_id'],'is_del' => 0])->find();
                if($params['divide'] > $channel_user->divide ){
                    throw new Exception('推广员分成比例不能大于渠道分成比例');
                }

                $res = PromoterModel::where(['user_id' => $user->user_id,'is_del' => 0])->find();
                if($res){
                    throw new Exception('已经是推广员了');
                }
                PromoterModel::create([
                    'channel_id' => $params['channel_id'],
                    'user_id' => $user->user_id,
                    'divide' => $params['divide'],
                    'divide_type' => $channel_user->divide_type
                ]);
            }else{
                //编辑
                $promoter = PromoterModel::where('is_del',0)->where('id',$params['id'])->find();
                $channel_user = Channel::where('id',$promoter->channel_id)->find();
                if($params['divide'] > $channel_user->divide ){
                    throw new Exception('推广员分成比例不能大于渠道分成比例');
                }
                $promoter->channel_id = $params['channel_id'];
                $promoter->divide = $params['divide'];
                $promoter->divide_type = $channel_user->divide_type;
                $promoter->save();
                //todo 再修改昵称
                $user = User::where('is_delete',0)->find($promoter->user_id);
                $user->nick_name = $params['nick_name'];
                $user->username = $params['username'];
                if(!empty($params['password']) && !empty($params['confirm_password'])){
                    $user->password = encryption_hash((string)$params['password']);
                }
                $user->save();
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            throwError($e->getMessage());
        }
    }

    /**
     * @param $username
     * @param $id
     */
    public function getReviewUsernameCheck($username,$id): bool
    {
        if(!$id){
            //新增
            $condition = [
                ['is_delete','=',0],
                ['username' ,'=',$username],
            ];
        }else{
            //编辑
            $promoter_user = PromoterModel::where(['is_del' => 0,'id' => $id])->find();
            if(!$promoter_user){
                throwError('不存在此推广员或已被删除');
            }
            $condition = [
                ['is_delete','=',0],
                ['username' ,'=',$username],
                ['user_id','<>',$promoter_user->user_id]
            ];
        }
        $user = User::where($condition)->find();
        if(!$user){
            return true;
        }
        return false;
    }



    /**删除
     * @param $id
     */
    public function delete($id):bool
    {
        $promoter = PromoterModel::where('is_del',0)->find($id);
        if(!$promoter){
            throwError('推广员不存在或已删除');
        }
        Db::startTrans();
        try {
            //todo 删除推广员同时将其下面的玩家同时解绑
            $promoter->is_del = 1;
            $promoter->save();
            Rel::update(['is_del' => 1],['promoter_user_id' => $promoter->user_id]);
            //同时将用户账户名置为空，避免账户重复
            UserModel::update(['username' => ''],['user_id' => $promoter->user_id]);

            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            return false;
        }
    }

    /**提现关闭、打开
     * @param $params
     */
    public function getFrozenWithDraw($params): bool
    {
        $promoter = PromoterModel::where('is_del',0)->find($params['id']);
        if(!$promoter){
            throwError('推广员不存在或已删除');
        }
        $promoter->is_with_draw = $params['is_with_draw'];
        return $promoter->save();
    }

}